#!/usr/local/bin/python2
# encoding: utf-8

# Public Domain (CC0) http://creativecommons.org/publicdomain/zero/1.0/

# This toy proxy will let you view local Gemini requests, as well as capsules in
# Geminispace via the mozz.us proxy. It will also open http/s links in a new
# window or tab.

# This is primarily a demonstration of local .gmi files, plus it should display
# properly formatted / files with the .gmi extension from http/s. If you want
# to explore Geminispace without a proper browser, you should probably use an
# online proxy directly instead of this.

from os import popen as sh
from os import environ
from urllib import urlopen

base = ""
pstate = 0

print "content-type: text/html charset=utf-8\n"

print "<head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"></head>"

print "<body style='font-family: monospace;'>"

def clean(text):
    for each in "!@#$%^&*()=+; []{}'|,<>`":
        text = text.replace(each, "")
    return text

def parselink(text, base):
    c = " ".join(text.split()[1:]).strip()
    text = text.split()[0] 
    if c == "":
        c = text

    if text[0:4].lower() == "http":
        if text[-4:].lower() == ".gmi":
            return "<a href='toygmi.py?u=" + text + "'>" + c + "</a>"
        else:
            return "<a href='" + text + "' target='#new'>" + c + "</a> (web)"

    if not "gemini://" in text.lower() and "gemini://" in base.lower():
        return "<a href='toygmi.py?u=" + base + text + "'>" + c + "</a>"
    else:
        return "<a href='toygmi.py?u=" + text + "'>" + c + "</a>"

def parsegmi(pstate, txt, base):
    if txt[0:3] == "```":
        if pstate == 1:
            return (0, "</pre>")
        else:
            return (1, "<pre>")
    if pstate == 1:
        return (1, txt.rstrip())
    else:
        if txt[0:3] == "=> ":
            return (0, parselink(txt[3:].rstrip(), base) + "<br>")
        if txt[0:2] == "> ":
            return (0, "<blockquote>" + txt[2:].rstrip() + "</blockquote>")
        if txt[0:2] == "# ":
            return (0, "<h1>" + txt[2:].rstrip() + "</h1>")
        if txt[0:3] == "## ":
            return (0, "<h2>" + txt[3:].rstrip() + "</h2>")
        if txt[0:4] == "### ":
            return (0, "<h3>" + txt[4:].rstrip() + "</h3>")        
        return (0, txt.rstrip() + "<br>")

files = sh("dir *.gmi /b").readlines()
files = "<br>".join(files)

files2 = sh("ls *.gmi").readlines()
files += "<br>".join(files2)

print "ToyGMI Proxy 0.01<br>"
print "Public Domain (CC0) http://creativecommons.org/publicdomain/zero/1.0/<br><br>"

if len(files):
    print "Local .gmi Files: "
    first = 1
    for each in files.split("<br>"):
        if first:
            print "<a href='toygmi.py?u=" + each + "'>" + each + "</a>"
            first = 0
        else:
            print "&nbsp;| <a href='toygmi.py?u=" + each + "'>" + each + "</a>"
else:
    print "No local .gmi files found<br>"


print "<pre>-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-</pre>"

try:
    f = open(clean(environ['QUERY_STRING'].split("u=")[1])).readlines()
    for each in f:
        pg = parsegmi(pstate, each, base)
        pstate = pg[0]
        print pg[1]
    base = ""
except:
    try:
        base = clean(environ['QUERY_STRING'].split("u=")[1])
        if base[0:4].lower() == "http" and base[-4:].lower() == ".gmi":
            f = str(urlopen(base).read()).replace(chr(13), "").split(chr(10))
            for each in f:
                try:
                    pg = parsegmi(pstate, each, base)  
                    print pg[1]
                except:
                    pass
                pstate = pg[0]
        else:
            u = "https://portal.mozz.us/" + base.replace("//","/").replace("gemini:/","gemini/") + "?raw=1"
            f = str(urlopen(u).read()).replace(chr(13), "").split(chr(10)) 
            for each in f:
                try:
                    pg = parsegmi(pstate, each, base)  
                    print pg[1]
                except:
                    pass
    except:
        pass

print "<br>"

print "</body>"



